import wsgiref.handlers
import os
import cgi
import primes
import main

from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from django.utils import simplejson
from google.appengine.ext import db

class Decoder(webapp.RequestHandler):

	def get(self):
		codes = []
		codes.append(self.request.get("row1")[0:3])
		codes.append(self.request.get("row1")[3:6])		
		codes.append(self.request.get("row1")[6:9])
		
		factors = []
		for code in codes:
			factors.append(primes.Primes.factorize(int(code)))
		
		query = db.Query(main.Wheel)
		
		query.filter('factor0 = ', factors[0]).filter('factor1 = ', factors[1]).filter('factor2 = ', factors[2])
		results = []
		
		if query.count() > 0:
			wheel = query[0]

			i = 0
			for code in codes:

				rowQuery = db.Query(main.WheelRow)
				rowQuery.filter('wheel = ',wheel.key()).filter('fieldCode = ', int(code)).filter('fieldIndex = ', i)
				
				if rowQuery.count() > 0:
					results.append(rowQuery[0].fieldValue)
				i = i + 1
				
		self.response.headers['Content-Type'] = 'text/text'
		for value in results:
			self.response.out.write(value + ',')
			